package com.app.utils;

import android.content.Context;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import com.app.application.MyApplication;
import com.app.config.AppConfig;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UtilityBase;
import com.lepu.app.fun.chat.core.ClientChatXmppImpl;
import com.lepu.app.main.activity.MainTabActivity;

import org.jivesoftware.smack.XMPPConnection;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 统计也面从后台进入前台
 * 这个类，必须在固定的包下，类名，方法名都不能变。通过从lib_core中，反射调用
 */
public class AppEnterTongJi implements AsyncRequest {

    public static final String REQUEST_ENTER_USE = "request_enter_use";

    private static AppEnterTongJi mInstance = null;

    public static AppEnterTongJi getInstance()
    {
        if(mInstance == null)
        {
            mInstance = new AppEnterTongJi();
        }
        return mInstance;
    }

    /**
     * 统计进入使用
     * @param context
     */
    public void requestEnterUse(Context context) {

        //test
        //clear();
    	//程序没有启动，不做前后台切换统计
    	if(MainTabActivity.getInstance() == null)
    	{
    		return;
    	}
        enterForegroundDoWith();

        String version = "";
        try {
            version = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject params = new JSONObject();
        try {
            params.put("DeviceID", Setting.DEVICEID);
            params.put("ApplicationID", Setting.APPLICATIONID);

            params.put("UserID", LoginUtil.getUserId());
            params.put("LoginToken", LoginUtil.getLoginToken());

            params.put("ClientVersion", version);
            params.put("ClientOSVersion",
                    AppManager.getDeviceSdkVersion(context));
            params.put("DeviceModel",
                    AppManager.getDeviceModel(context));
            params.put("DeviceSN",
                    AppManager.getDeviceUniqueId(context));
            params.put("ClientIP",
                    AppManager.getDeviceIpAddress(context));

            String umengChannel = UtilityBase.getAppMetedata(context,
                    "UMENG_CHANNEL");
            params.put("AppChannel", umengChannel);

            params.put("Longitude", LocationUtil.getInstance().mLongitude);//经度
            params.put("Latitude", LocationUtil.getInstance().mLatitude);//纬度

            params.put("StartupTime",getDayJsonArray(true));

        } catch (JSONException e) {
            e.printStackTrace();
        }
        map.put("ht", params);

        ApiClient.http_post(Setting.getStartupLogUrl(), map, null, this,
                REQUEST_ENTER_USE, false);
    }

    private void clear()
    {
        AppConfig.setConfig(MyApplication.getInstance(), Const.CONFIG_APP_ENTER_TONG_JI, "");
    }

    private JSONArray getDayJsonArray(boolean getPre)
    {
        JSONArray jsonArray = null;

        String currentDay = DateUtilBase.stringFromDate(new Date(), DateUtilBase.DATE_ALL_ALL);
        String oldDayString = AppConfig.getConfigString(MyApplication.getInstance(), Const.CONFIG_APP_ENTER_TONG_JI, "");
        if(TextUtils.isEmpty(oldDayString)){
            jsonArray = new JSONArray();
            jsonArray.put(currentDay);
        }else{
            try {
                jsonArray = new JSONArray(oldDayString);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if(!getPre){
                jsonArray.put(currentDay);
            }
        }
        return jsonArray;
    }

    private void enterForegroundDoWith()
    {
//        try
//        {
//            LogUtilBase.LogD(null,"enterForegroundDoWith");
//            XMPPConnection connection = ClientChatXmppImpl.getInstance()
//                    .getConnection();
//            if (connection == null || !connection.isConnected()) {
//                ClientChatXmppImpl.getInstance().setConnectionClosed(true);
//
//                LoginUtil.loginOpenFire();
//            }
//        }catch (Exception e){
//
//        }
    }

    @Override
    public void RequestComplete(Object object, Object data) {
        if (object.equals(REQUEST_ENTER_USE)) {
            LogUtilBase.LogD(null, REQUEST_ENTER_USE + "_success");

            clear();
        }
    }

    @Override
    public void RequestError(Object object, int errorId, String errorMessage) {
        if (object.equals(REQUEST_ENTER_USE)) {
            LogUtilBase.LogD(null, REQUEST_ENTER_USE + "_fail");

            AppConfig.setConfig(MyApplication.getInstance(), Const.CONFIG_APP_ENTER_TONG_JI, getDayJsonArray(false).toString());
        }
    }


}
